#!/bin/bash

LOCAL_PATH=$pwd
PATH_DIR_BUSYBOX_DIR=../busybox-1.31.1/
PATH_DIR_CROSS_COMPILER=../toolchains/gcc-linaro-7.5.0-2019.12-i686_arm-linux-gnueabi/

set -e


rm -rf ./rootfs
rm -rf a9rootfs.ext3
rm -rf tmpfs

mkdir tmpfs
mkdir rootfs

echo "---Create dirs---"
cd rootfs
mkdir etc
mkdir dev
mkdir lib
mkdir proc
mkdir sys
mkdir var
mkdir tmp
mkdir root
mkdir opt
mkdir mnt

echo "Enter etc and create etc/fstab etc/inittab etc/init.d/rcS etc/profile"
cd etc
touch fstab
touch inittab
mkdir init.d
touch init.d/rcS
chmod +x init.d/rcS
touch profile
echo "Exit from etc dir"
cd ..

echo "########  /etc/init.d/rcS ########" > etc/init.d/rcS
echo "#!/bin/sh" >> etc/init.d/rcS
echo "/bin/mount -a" >> etc/init.d/rcS

echo "########  /etc/inittab ########" > etc/inittab
echo "::sysinit:/etc/init.d/rcS" >> etc/inittab
echo "::askfirst:-/bin/sh" >> etc/inittab
echo "::restart:/sbin/init" >> etc/inittab
echo "::ctrlaltdel:/sbin/reboot" >> etc/inittab

echo "#device mount-point            type     options   dump fsck order" > etc/fstab
echo "proc      /proc                proc    defaults      0       0" >> etc/fstab
echo "tmpfs     /tmp                 tmpfs   defaults      0       0" >> etc/fstab
echo "sysfs     /sys                 sysfs   defaults      0       0 " >> etc/fstab
echo "tmpfs     /dev                 tmpfs   defaults      0       0" >> etc/fstab
echo "debugfs   /sys/kernel/debug/  debugfs  defaults      0       0" >> etc/fstab

echo "#######  /etc/profile ########" > etc/profile
echo "#!/bin/sh " >> etc/profile
echo "export PS1='[$USER@$HOSTNAME \w]\# '" >> etc/profile
echo "PATH=/bin:/sbin:/usr/bin:/usr/sbin" >> etc/profile
echo "LD_LIBRARY_PATH=/lib:/usr/lib:$LD_LIBRARY_PATH" >> etc/profile
echo "export PATH LD_LIBRARY_PATH" >> etc/profile

echo "exit from rootfs dir"
cd ..
echo "---make dirs done---"


cp -a $PATH_DIR_BUSYBOX_DIR/_install/* -r ./rootfs
cp -a $PATH_DIR_CROSS_COMPILER/lib/* ./rootfs/lib/

sudo mknod rootfs/dev/tty1 c 4 1
sudo mknod rootfs/dev/tty2 c 4 2
sudo mknod rootfs/dev/tty3 c 4 3
sudo mknod rootfs/dev/tty4 c 4 4

dd if=/dev/zero of=a9rootfs.ext3 bs=1M count=48
mkfs.ext3 a9rootfs.ext3

sudo mount -t ext3 a9rootfs.ext3 tmpfs/ -o loop
sudo cp -r rootfs/* tmpfs/
sudo umount tmpfs

#rm -rf ./rootfs
chmod 777 rootfs
rm -rf tmpfs 

exit 0

